package com.plant.user.service.impl;
import com.plant.common.domain.User;
import com.plant.common.result.Result;
import com.plant.user.domain.VO;
import com.plant.user.mapper.UserMapper;
import com.plant.user.service.UserService;
import com.plant.user.utils.AddUserUtils;
import com.plant.user.utils.SmsUtils;
import com.plant.user.utils.ChinesePattern;
import lombok.extern.slf4j.Slf4j;
import com.plant.user.enumm.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AddUserUtils addUserUtils;


    @Override
    public User login(String phone, String password) {
        try {
            User us = userMapper.login(phone, password);
            if (us != null){
                try {
                    //向redis中存入一份 但不存储密码
                    redisTemplate.opsForValue().set(us.getPhone(),"logged_in_user");
                }catch (Exception e){
                    log.error("Failed to start user in Redis:{}",e.getMessage());
                }
            }
            return us;
        }catch (Exception e){
            log.error("Database query failed during login: {}",e.getMessage());
            return null;
        }
    }

    @Override
    public int recharge(User user) {
        int i = userMapper.recharge(user);
        return i;
    }

    @Override
    public User findById(Integer id) {
        return userMapper.findById(id);
    }


    @Override
    public Result addUser(User user) {
        String phone = user.getPhone();
        if (phone == null || phone.isEmpty()) {
            return Result.fail(ErrorCode.PHONE_CANNOT_BE_EMPTY.getCode(),ErrorCode.PHONE_CANNOT_BE_EMPTY.getMessage());
        }
        String password = user.getPassword();
        String value1 = user.getValue1();
        if (!addUserUtils.isValidPassword(password, value1)) {
            // 处理密码校验失败的情况
            return Result.fail1(addUserUtils.getPasswordErrorResultCode(password,value1), addUserUtils.getPasswordErrorMessage(value1));
        }
        try {
            // 生成随机用户名
            user.setUsername(addUserUtils.generateRandomUsername(8));
            user.setType(1);
            user.setStatus("1");
            user.setDel(0);
            user.setIsPaid(1);

            Integer i = userMapper.addUser(user);
            if (i > 0) {
                return Result.ok();
            } else {
                return Result.fail(ErrorCode.USER_ADD_FAILED.getCode(), "添加失败");
            }
        } catch (Exception e) {
            return Result.fail(ErrorCode.USERNAME_GENERATION_FAILED.getCode(), "生成用户名时出现错误");
        }

    }

    @Override
    public Result updateUser(VO vo) {
        //获取手机号
        String phone = vo.getPhone();
        if (phone == null || phone.isEmpty()){
         return Result.fail(ErrorCode.PHONE_CANNOT_BE_EMPTY.getCode(),ErrorCode.PHONE_CANNOT_BE_EMPTY.getMessage());
        }
        //获取密码
        String password = vo.getPassword();
        if (!addUserUtils.ValidPassword(password)) {
            if (password == null || password.isEmpty()) {
                return Result.fail(ErrorCode.PHONE_CANNOT_BE_EMPTY.getCode(),ErrorCode.PHONE_CANNOT_BE_EMPTY.getMessage());
            } else if (ChinesePattern.isChinese(password)) {
                return Result.fail(ErrorCode.PASSWORD_CONTAINS_CHINESE.getCode(), ErrorCode.PASSWORD_CONTAINS_CHINESE.getMessage());
            } else {
                return Result.fail(ErrorCode.PASSWORD_LENGTH_INVALID.getCode(), ErrorCode.PASSWORD_LENGTH_INVALID.getMessage());
            }
        }
        try {
            int i = userMapper.updateUser(vo);
            if (i > 0) {
                return Result.ok();
            } else {
                return Result.fail(ErrorCode. USERNAME_GENERATION_FAILED.getCode(), ErrorCode. USERNAME_GENERATION_FAILED.getMessage());
            }
        } catch (Exception e) {
            return Result.fail(ErrorCode. USERNAME_GENERATION_FAILED.getCode(), "修改失败：" + e.getMessage());
        }
    }


    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    public User chaxun(String phone) {
        //加密手机号
        return userMapper.chaxun(phone);
    }

    @Override
    public String fsCode(User user) {
        // 随机数六位纯数字
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        try {
            SmsUtils.sendSms(user.getPhone(), code);
            return code;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }
    @Override
    public int withdrawal(User user) {
        return userMapper.withdrawal(user);
    }

    @Override
    public int updateUserType(Integer id) {
        return userMapper.updateUserType(id);
    }

    @Override
    public int SignOut(String phone) {
        redisTemplate.delete(phone);
        return 0;
    }




}
